package com.tqz.core;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.lang.Nullable;

import java.lang.reflect.Proxy;

/**
 * <p>实现 {@link FactoryBean} 接口，
 * 从容器中获取一个bean，从而插手该bean的创建过程并返回到容器中。
 *
 * @author tianqingzhao
 * @since 2021/7/8 12:02
 */
public class RemoteCallFactoryBean<T> extends AbstractDiscoveryClientSupport implements FactoryBean<T> {

    private Class<T> targetClass;

    public RemoteCallFactoryBean(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Nullable
    @Override
    public T getObject() throws Exception {
        RemoteCallProxy remoteCallProxy = new RemoteCallProxy(getDiscoveryClient(), targetClass);

        return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class<?>[]{targetClass}, remoteCallProxy);
    }

    @Nullable
    @Override
    public Class<?> getObjectType() {
        return targetClass;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
